﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietPremier.Areas.AdminCP.Models;
using MvcLibrary.Repository;
using System.IO;

namespace VietPremier.Areas.AdminCP
{
    public class AdminTravelCityController : Controller
    {
        #region "Index"
        public ActionResult Index(int idTravelProduct)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                TravelCityModel model = new TravelCityModel();                
                //sử dụng query lấy tên thành phố và id
                EntityTravelProduction travelProduct = db.EntityTravelProductions.FirstOrDefault(o => o.Id == idTravelProduct);
                if (travelProduct != null)
                {
                    model.travelProduct.Id = travelProduct.Id;
                    model.travelProduct.Name = travelProduct.Name;

                    foreach (var travelCity in db.EntityTravelCities.Where(o => o.IdTravelProduction == travelProduct.Id))
                    {
                        if (travelCity != null)
                        {
                            model.listTravelCity.Add(new TravelCity()
                            {
                                Id = travelCity.Id,
                                IdTravelProduction = travelCity.IdTravelProduction,
                                Name = travelCity.Name,
                                Description = travelCity.Description,
                                Price = travelCity.Price,
                                Time = travelCity.Time,
                                Duration = travelCity.Duration,
                                Body = travelCity.Body,
                                Itinerary = travelCity.Itinerary,
                                Note = travelCity.Note,
                                Image = travelCity.Image,
                                Position = travelCity.Position,
                                Hot = travelCity.Hot,
                                //<!-- SEO -->
                                Titletag = travelCity.Titletag,
                                Meta_description = travelCity.Meta_description,
                                Meta_keyword = travelCity.Meta_keyword
                            });
                        }
                    }
                    return View(model);
                }
                return View(model);
            }
        }
        #endregion //edit

        #region "Delete"
        public string Delete(int id)
        {
            try
            {
                dbVietPremierDataContext db = new dbVietPremierDataContext();
                EntityTravelCity item = db.EntityTravelCities.Where(p => p.Id == id).Single();
                //delete file cu
                if (item.Image != null)
                {
                    string fileToDelete = Path.Combine(Server.MapPath("~/Content/upload/travelcity/"), item.Image); // file hinh cu
                    System.IO.File.Delete(fileToDelete);
                }
                db.EntityTravelCities.DeleteOnSubmit(item);
                db.SubmitChanges();
                return "Ok";
            }
            catch
            {
                return "Error";
            }
        }
        #endregion //delete

        #region "Insert"
        public ActionResult Insert(int idTravelProduct)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                TravelCityModel model = new TravelCityModel();
                EntityTravelProduction travelProduct = db.EntityTravelProductions.FirstOrDefault(o => o.Id == idTravelProduct);
                if (travelProduct != null)
                {
                    model.travelProduct.Id = travelProduct.Id;
                    model.travelProduct.Name = travelProduct.Name;
                    foreach (var travelStyle in db.EntityStyles)
                    {
                        model.listTravelStyle.Add(new TravelStyle()
                        {
                            Id = travelStyle.Id,
                            Name = travelStyle.Name
                        });
                    }
                }
                return View(model);
            }
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Insert(int idTravelProduct, TravelCity model, HttpPostedFileBase Image, int[] IdStyle)
        {
            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                EntityTravelCity travelCity = new EntityTravelCity();
                travelCity.IdTravelProduction = idTravelProduct;
                //travelCity.IdStyle = IdStyle;
                travelCity.Name = model.Name;
                travelCity.Price = model.Price;
                travelCity.Description = model.Description;
                travelCity.Body = model.Body;
                travelCity.Time = model.Time;
                travelCity.Duration = model.Duration;
                travelCity.Itinerary = model.Itinerary;
                travelCity.Note = model.Note;
                travelCity.Position = model.Position;
                if (Image != null && Image.ContentLength > 0)
                {
                    int kb = Image.ContentLength / 1024; //file size kb
                    if (kb >= 2048) // file qua lon
                    {
                        return RedirectToAction("Index", "Error", new { errorMsg = "Can not upload image" });
                    }

                    ImageHelper imgHelper = new ImageHelper();
                    string encodestring = imgHelper.encodeImageFile(Image);

                    if (encodestring == "!")
                        return RedirectToAction("Index", "Error", new { errorMsg = "Can not upload image" });

                    var path = Path.Combine(Server.MapPath("~/Content/upload/travelcity/"), encodestring);
                    Image.SaveAs(path);

                    travelCity.Image = encodestring;
                }
                //<!-- SEO -->
                travelCity.Titletag = model.Titletag;
                travelCity.Meta_description = model.Meta_description;
                travelCity.Meta_keyword = model.Meta_keyword;

                db.EntityTravelCities.InsertOnSubmit(travelCity);
                db.SubmitChanges();


                var query = from p in db.EntityTravelCities
                                   select p;
                int Count = query.Count() - 1; // tru phan tu 0
                int IdTravelCity = query.Skip(Count).FirstOrDefault().Id;

                for (int i = 0; i < IdStyle.Count(); i++)
                {
                    EntityTravelStyle travelStyle = new EntityTravelStyle();
                    travelStyle.IdTravelCity = IdTravelCity;
                    travelStyle.IdStyle = IdStyle[i];
                    db.EntityTravelStyles.InsertOnSubmit(travelStyle);
                    db.SubmitChanges();
                }
                


                return RedirectToAction("Index", "AdminTravelCity", new { idTravelProduct = idTravelProduct });
            }
        }
        #endregion

        #region "Edit"
        public ActionResult Edit(int idTravelCity)
        {
            TravelCityModel model = new TravelCityModel();

            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                EntityTravelCity travelCity = db.EntityTravelCities.FirstOrDefault(o => o.Id == idTravelCity);

                if (travelCity != null)
                {
                    model.travelCity.Id = travelCity.Id;
                    model.travelCity.IdTravelProduction = travelCity.IdTravelProduction;
                    model.travelCity.Name = travelCity.Name;
                    model.travelCity.Price = travelCity.Price;
                    model.travelCity.Description = travelCity.Description;
                    model.travelCity.Time = travelCity.Time;
                    model.travelCity.Duration = travelCity.Duration;
                    model.travelCity.Body = travelCity.Body;
                    model.travelCity.Itinerary = travelCity.Itinerary;
                    model.travelCity.Note = travelCity.Note;
                    model.travelCity.Image = travelCity.Image;
                    model.travelCity.Position = travelCity.Position;
                    //<!--SEO -->
                    model.travelCity.Titletag = travelCity.Titletag;
                    model.travelCity.Meta_description = travelCity.Meta_description;
                    model.travelCity.Meta_keyword = travelCity.Meta_keyword;
                    
                    //lay danh sach travelstyle trong bang entityStyles
                    foreach (var style in db.EntityStyles)
                    {
                        model.listTravelStyle.Add(new TravelStyle()
                        {
                            Id = style.Id,
                            Name = style.Name
                        });
                    }
                }
                return View(model);
            }

        }

        [HttpPost]
        public JsonResult GetDetail(int idTravelCity)
        {
            TravelCity model = new TravelCity();
            model.Id = -1;

            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                EntityTravelCity travelCity = db.EntityTravelCities.FirstOrDefault(o => o.Id == idTravelCity);

                if (travelCity != null)
                {
                    model.Id = travelCity.Id;
                    model.IdTravelProduction = travelCity.IdTravelProduction;
                    model.Name = travelCity.Name;
                    model.Price = travelCity.Price;
                    model.Description = travelCity.Description;
                    model.Time = travelCity.Time;
                    model.Duration = travelCity.Duration;
                    model.Body = travelCity.Body;
                    model.Itinerary = travelCity.Itinerary;
                    model.Note = travelCity.Note;
                    model.Image = travelCity.Image;
                    model.Position = travelCity.Position;
                    //<!--SEO -->
                    model.Titletag = travelCity.Titletag;
                    model.Meta_description = travelCity.Meta_description;
                    model.Meta_keyword = travelCity.Meta_keyword;

                    //lay danh sach travelstyle trong bang entityTravelStyles
                    foreach (var travelStyle in db.EntityTravelStyles.Where(o => o.IdTravelCity == idTravelCity))
                    {
                        EntityStyle style = db.EntityStyles.FirstOrDefault(o => o.Id == travelStyle.IdStyle);
                        model.listTravelStyle.Add(new TravelStyle()
                        {
                            Id = style.Id,
                            Name = style.Name
                        });
                    }
                }
                return Json(model);
            }

        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int idTravelCity, TravelCity model, HttpPostedFileBase Image, int[] IdStyle )
        {

            using (dbVietPremierDataContext db = new dbVietPremierDataContext())
            {
                //check Id 
                EntityTravelCity travelCity = db.EntityTravelCities.Where(p => p.Id == idTravelCity).FirstOrDefault();
                travelCity.Position = model.Position;
                travelCity.Itinerary = model.Itinerary;
                travelCity.Note = model.Note;
                if (Image != null && Image.ContentLength > 0)
                {
                    int kb = Image.ContentLength / 1024; //file size kb
                    if (kb >= 2048) // file qua lon
                    {
                        return RedirectToAction("Index", "Error", new { errorMsg = "Images must be less than 2MB." });
                    }
                    //delete file cu
                    if (travelCity.Image != null)
                    {
                        string fileToDelete = Path.Combine(Server.MapPath("~/Content/upload/travelcity/"), travelCity.Image); // file hinh cu
                        System.IO.File.Delete(fileToDelete);
                    }

                    ImageHelper imgHelper = new ImageHelper();
                    string encodestring = imgHelper.encodeImageFile(Image);

                    if (encodestring == "!")
                        return RedirectToAction("Index", "Error", new { errorMsg = "Can not upload image" });

                    var path = Path.Combine(Server.MapPath("~/Content/upload/travelcity/"), encodestring);
                    Image.SaveAs(path);

                    travelCity.Image = encodestring;
                }
                travelCity.Name = model.Name;
                travelCity.Price = model.Price;
                travelCity.Description = model.Description;
                travelCity.Time = model.Time;
                travelCity.Duration = model.Duration;
                travelCity.Body = model.Body;
             
                //<!--SEO -->
                travelCity.Titletag = model.Titletag;
                travelCity.Meta_description = model.Meta_description;
                travelCity.Meta_keyword = model.Meta_keyword;

                db.SubmitChanges();

                foreach (var travelStyle in db.EntityTravelStyles.Where(o => o.IdTravelCity == idTravelCity))
                {
                    EntityTravelStyle item = db.EntityTravelStyles.Where(p => p.Id == travelStyle.Id).Single();
                    if (item != null)
                    {
                        db.EntityTravelStyles.DeleteOnSubmit(item);
                        db.SubmitChanges();
                    }

                }

                int count = 0;
                count =  db.EntityTravelStyles.Where(o => o.IdTravelCity == idTravelCity).Count();
                if (count > 0)
                {
                    if (count > 0 && IdStyle == null)
                    {
                    }
                }
                else
                {
                    if (IdStyle != null)
                    {
                        for (int i = 0; i < IdStyle.Count(); i++)
                        {
                            EntityTravelStyle newTravelStyle = new EntityTravelStyle();
                            newTravelStyle.IdTravelCity = idTravelCity;
                            newTravelStyle.IdStyle = IdStyle[i];
                            db.EntityTravelStyles.InsertOnSubmit(newTravelStyle);
                            db.SubmitChanges();

                        }
                    }
                    else
                    {
                    }
                }
                return RedirectToAction("Index", "AdminTravelCity", new { idTravelProduct = travelCity.IdTravelProduction });
            }
        }

        #endregion //edit

        [HttpPost]
        public ActionResult SetStatus(int id)
        {
            dbVietPremierDataContext db = new dbVietPremierDataContext();

            EntityTravelCity travelCity = db.EntityTravelCities.FirstOrDefault(o => o.Id == id);
            if (travelCity.Hot.Equals(true))
            {
                travelCity.Hot = false;
            }
            else
            {
                travelCity.Hot = true;
            }
            db.SubmitChanges();
            return Content("Ok");
        }

    }
}
